package com.yilin.medical.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;

public class JxStringUtils {

	public static boolean isNullOrEmpty(String text) {
		if (text == null || "".equals(text.trim()) || text.trim().length() == 0
				|| "null".equals(text.trim())) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获得MD5加密字符�?
	 * 
	 * @param str
	 *            字符�?
	 * @return
	 */
	public static String getMD5Str(String str) {
		MessageDigest messageDigest = null;
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] byteArray = messageDigest.digest();
		StringBuffer md5StrBuff = new StringBuffer();
		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}
		return md5StrBuff.toString();
	}

	/**
	 * 对流转化成字符串
	 * 
	 * @param is
	 * @return
	 */
	public static String getStringByStream(InputStream is) {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = in.readLine()) != null) {
				buffer.append(line + "\n");
			}
			return buffer.toString().replaceAll("\n\n", "\n");
		} catch (OutOfMemoryError o) {
			System.gc();
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 对流转化成字符串
	 * 
	 * @param is
	 * @return
	 */
	public static String getContentByString(InputStream is) {
		try {
			if (is == null)
				return null;
			byte[] b = new byte[1024];
			int len = -1;
			StringBuilder sb = new StringBuilder();
			while ((len = is.read(b)) != -1) {
				sb.append(new String(b, 0, len));
			}
			return sb.toString();
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 对图片进行动态调�?
	 * 
	 * @param coverimg
	 * @param width
	 * @param height
	 * @return
	 */
	public static String getImgPath(String coverimg, int width, int height) {
		if (isNullOrEmpty(coverimg)) {
			return "";
		}
		if (!coverimg.startsWith("http")) {
			return coverimg;
		}
		try {
			URL url = new URL(coverimg);
			if (url.getHost().indexOf("soufun") == -1) {
				return coverimg;
			}
		} catch (MalformedURLException e) {
			return "";
		}

		String http = coverimg.substring(7);
		String head = http.substring(0, http.indexOf("/"));
		String xurl = coverimg.replace("http://" + head, "");
		xurl = xurl.substring(0, xurl.lastIndexOf("."));
		String xend = coverimg.substring(coverimg.lastIndexOf("."));
		String h = String.valueOf(height);
		if (width == 480 && height == 440) {

		} else {
			h = h + "c4";
		}
		if (coverimg.indexOf("viewimage") > -1) {
			coverimg = coverimg.substring(0, coverimg.lastIndexOf("/")) + "/"
					+ width + "x" + h + xend;
		} else {
			coverimg = "http://" + head + "/viewimage" + xurl + "/" + width
					+ "x" + h + xend;
		}
		return coverimg;
	}

	public static SpannableString getMoreStyle(SpannableString WordtoSpan,
			String text, double size, int start, int end, int color, int style) {
		if (WordtoSpan == null) {
			WordtoSpan = new SpannableString(text);
		}
		WordtoSpan.setSpan(new RelativeSizeSpan((float) size), start, end,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		WordtoSpan.setSpan(new StyleSpan(style), start, end,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		WordtoSpan.setSpan(new ForegroundColorSpan(color), start, end,
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

		return WordtoSpan;
		// WordtoSpan = new SpannableString("�? 房源套数 �?" + result.RoomCount +
		// "�?");
		// WordtoSpan.setSpan(new RelativeSizeSpan((float)1.2),
		// 0, 8,
		// Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		// WordtoSpan.setSpan( new StyleSpan(android.graphics.Typeface.BOLD),
		// 0, 8,
		// Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		// WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLACK),
		// 0, 8,
		// Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

	}

	/**
	 * 电话号码验证
	 * 
	 * @param phoneNumber
	 *            手机号码
	 * @return
	 */
	public static boolean validatePhoneNumber(String phoneNumber) {
		Pattern pattern = Pattern
				.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
		Matcher m = pattern.matcher(phoneNumber);
		return m.matches();
	}

	public static int getScreenHeight(Activity mActivity) {
		DisplayMetrics dm = new DisplayMetrics();
		mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenHeight = dm.heightPixels;
		return screenHeight;
	}

	public static int getScreenWidth(Activity mActivity) {
		DisplayMetrics dm = new DisplayMetrics();
		JxLogUtil.i("mActivity.getWindowManager() = "
				+ mActivity.getWindowManager());
		mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);// 报错
		int screenWidth = dm.widthPixels;
		return screenWidth;
	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}
	public static String returnStringFloat(String num) {
		if(isNullOrEmpty(num)){
			return num;
		}
		float temp=Float.parseFloat(num);
		if (temp % 1.0 == 0) {
			int t=(int)temp;
			return String.valueOf(t);
		}
		return num;
	}
    public static String returnStringDouble(String num) {
		if(num==null){
			return num;
		}
        double temp=Double.parseDouble(num);
		if (temp % 1.0 == 0) {
            long t= (long)temp;
			return String.valueOf(t);
		}
		return num;
	}
	public static String returnStringInt(String num) {
		if(num==null){
			return num;
		}
		float temp=Float.parseFloat(num);
		num=(int)temp+"";
		return num;
	}

    /**
     * 使用java正则表达式去掉多余的.与0
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s){
        if(s.indexOf(".") > 0){
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }


    public static  String getNumberByStr(String str,String patternStr){
        Pattern pattern = Pattern.compile(patternStr);
        Matcher m = pattern.matcher(str);
        String number = "";
        while (m.find()){
            number += m.group();
        }
        return number;
    }
    public static  Integer  getNumberByStr(String str){
        String number = "";
        if(str != null && !"".equals(str)) {
            for (int i = 0; i < str.length(); i++) {
                if (str.charAt(i) >= 48 && str.charAt(i) <= 57) {
                    number += str.charAt(i);
                }
            }
        }
        return Integer.parseInt(number);
    }
}
